package study.designpattern.interpreter;

import java.util.Stack;

public class Evaluator {
    Stack<Integer> stackValue = new Stack();
    Stack stackExpression = new Stack();
    
    public Evaluator(String expression) {
        expression = expression.replaceAll("[+,-]", ":$0:");
        String[] tokens = expression.split(":");
        for(String token:tokens){
            if(token.equals("+")){
                Expression subExpression = new Plus();
                stackExpression.add(subExpression);
            }
            else if(token.equals("-")){
                Expression subExpression = new Minus();
                stackExpression.add(subExpression);
            }else{
                int value = Integer.parseInt(token);
                if(!stackExpression.isEmpty()){
                    Expression subExpression = (Expression) stackExpression.pop();
                    value = subExpression.interprete(stackValue.pop(), value);
                }
                stackValue.push( value);
            }
        }
    }
    public int interprete(){
        return stackValue.pop();
    }
}
